<template>
  <view class="deviceConnectRow">
    <view class="title"> 连接设备 </view>
    <view class="deviceSelect">
      <view
        class="deviceItem"
        v-for="(item, index) in deviceList"
        :key="index"
        @click="changeDevice(index)"
      >
        <view class="deviceLogo">
          <image :src="item.deviceLogo" mode=""></image>
        </view>
        <view class="deviceInfo">
          <view class="localName">
            {{ item.localName }}
          </view>
          <view class="introduce">
            {{ item.introduce }}
          </view>
        </view>
        <view class="selectIcon" v-if="selectDevice == index">
          <image src="../static/dui.png" mode=""></image>
        </view>
      </view>
    </view>
    <view class="bluetoothRow" v-if="selectDevice != 0">
      <view class="tip">
        <view class="logo">
          <image src="../static/bluetooth.png" mode=""></image>
          <view class="text"> 蓝牙 </view>
        </view>
        <view class="switch">
          <!-- 	<view class="cricle">

					</view> -->
          {{ BLEStatus ? "已开启" : "未开启" }}
        </view>
      </view>
      <view class="bluetoothList">
        <view class="header">
          <view class="blueTitle"> 可用设备 </view>
          <view class="icon" @click="handleRefesh">
            <image src="../static/refesh.png" mode=""></image>
          </view>
        </view>
        <view class="bluetoothRow" v-show="bluetoothList.length > 0">
          <view
            class="bluetoothItem"
            v-for="(item, index) in bluetoothList"
            :key="index"
            @click="connectBLE(item)"
          >
            <view class="bluetoothInfo">
              <view class="name">
                {{ item.name }}
              </view>
              <view class="status">
                <text>
                  {{
                    item.name == "WT901BLE67"
                      ? deviceData.localName == "WT901BLE67"
                        ? "已连接"
                        : "可配对"
                      : "不可配对"
                  }}</text
                >
                <view class="statusEnegry" v-show="item.RSSI > -120"> </view>
                <view class="statusEnegry" v-show="item.RSSI > -90"> </view>
                <view class="statusEnegry" v-show="item.RSSI > -70"> </view>
                <view class="statusEnegry" v-show="item.RSSI > -40"> </view>

                <view class="statusEnegryNo" v-show="item.RSSI < -40"> </view>
                <view class="statusEnegryNo" v-show="item.RSSI < -70"> </view>
                <view class="statusEnegryNo" v-show="item.RSSI < -90"> </view>
                <view class="statusEnegryNo" v-show="item.RSSI < -120"> </view>
              </view>
              <view
                class="successSelect"
                v-show="deviceData.localName == item.localName"
              >
                <image src="../static/dui2.png" mode=""></image>
              </view>
            </view>
          </view>
        </view>
        <view class="" v-show="bluetoothList.length <= 0"> 暂无设备 </view>
      </view>
    </view>

    <view class="blueInfo" v-if="selectDevice != 0">
      <view class="connectTitle">
        <image src="../static/info.png" mode=""></image>
        <text>连接说明</text>
      </view>
      <view class="tipText"> ·请确保设备已开启并处于配对状态 </view>
      <view class="tipText"> ·请保持设备在手机周围 </view>
      <view class="tipText"> ·请重启外部设备 </view>
    </view>
  </view>
</template>

<script>
import tool from "@/utils/tool.js";
export default {
  data() {
    return {
      deviceList: [
        {
          deviceLogo: "../static/phone.png",
          localName: "手机",
          introduce: "使用手机进行训练",
        },
        {
          deviceLogo: "../static/deviceLogo.png",
          localName: "外部设备",
          introduce: "使用智训蓝牙设备进行训练",
        },
      ],
      bluetoothList: [], //当前搜索的蓝牙列表
      BLEStatus: false, //当前蓝牙开启状态
      deviceData: {}, //连接的设备信息
      selectDevice: 0, //0-手机 1-外设
    };
  },

  onShow() {
    let deviceData = uni.getStorageSync("deviceData") || {};
    this.deviceData = deviceData;
    console.log("--------", this.deviceData);
    if (!deviceData?.localName) {
      this.changeDevice(0);
    } else {
      if (deviceData?.localName == "手机") {
        this.changeDevice(0);
      } else {
        this.changeDevice(1);
      }
    }
    // tool.initBluetoothConnectionListener((res) => {
    // 		console.log('连接/断开连接设备',res)
    // })
    uni.onBLEConnectionStateChange((res) => {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      console.log("连接/断开连接设备", res);
      console.log(
        `device ${res.deviceId} state has changed, connected: ${res.connected}`
      );
      if (!res.connected) {
        uni.showToast({
          title: "连接断开",
          icon: "error",
        });
        uni.setStorageSync("deviceData", {
          localName: "手机",
        });
        this.deviceData = {
          localName: "手机",
        };
      }
    });
  },
  methods: {
    // 点击刷新
    async handleRefesh() {
      await this.startDiscovery();
      uni.showToast({
        icon: "none",
        title: "刷新成功",
      });
    },
    // 点击链接蓝牙
    connectBLE(e) {
      if (this.deviceData.localName == "WT901BLE67") {
        let that = this;
        uni.showModal({
          title: "提示",
          content: "要取消连接吗",
          success(res) {
            if (res.confirm) {
              tool.closeOnBLE();
              tool.closeBLEContent(that.deviceData.deviceId);
              that.startDiscovery();
              uni.setStorageSync("deviceData", {
                localName: "手机",
              });
              that.deviceData = {
                localName: "手机",
              };
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      }
      if (e.localName == "WT901BLE67") {
        // 连接设备
        uni.showLoading({
          title: "连接中",
        });
        this.connectDevice(e);
      } else {
        uni.showToast({
          title: "此设备不可连接",
          icon: "none",
        });
      }
    },
    // 点击切换设备
    changeDevice(e) {
      this.selectDevice = e;
      if (this.selectDevice == 1) {
        // 外设
        this.initializationBLE();
      } else {
        // 手机
        console.log(this.deviceData);
        if (this.deviceData?.localName != "手机") {
          // tool.closeBLEContent(this.deviceData.deviceId)
          tool.closeOnBLE();
          tool.closeBLEModal();
        }
        this.deviceData = {
          localName: "手机",
        };
        this.bluetoothList = [];
        uni.stopBluetoothDevicesDiscovery();
        uni.setStorageSync("deviceData", this.deviceData);
      }
    },
    // 初始化蓝牙
    initializationBLE() {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log("初始化蓝牙模块成功", res);
          this.BLEStatus = true;
          // 开始搜索蓝牙设备
          this.startDiscovery();
        },
        fail: (err) => {
          console.error("初始化蓝牙模块失败", err);
          this.BLEStatus = false;
          if (err.errCode === 10001) {
            wx.showModal({
              title: "提示",
              content: "请打开系统蓝牙",
              showCancel: false,
            });
          } else {
            wx.showModal({
              title: "提示",
              content: "请检查蓝牙状态",
              showCancel: false,
            });
          }
        },
      });
    },
    // 搜索设备
    async startDiscovery() {
      uni.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: false,
        success: (res) => {
          console.log("开始搜索蓝牙设备", res);
          this.BLEStatus = true;
          // 监听发现新设备事件
          uni.onBluetoothDeviceFound((res) => {
            console.log("监听到新设备");
            uni.getBluetoothDevices({
              success: (res) => {
                console.log(res.devices);
                this.bluetoothList = res.devices;
              },
              fail: (error) => {
                uni.showToast({
                  title: `查找错误${error}`,
                  icon: "none",
                });
              },
            });
          });
        },
        fail: (err) => {
          uni.showToast({
            title: `搜索蓝牙设备失败${err}`,
            icon: "none",
          });

          this.BLEStatus = false;
        },
      });
    },
    // 连接设备
    connectDevice(e) {
      uni.createBLEConnection({
        deviceId: e.deviceId,
        success: (res) => {
          console.log("连接蓝牙设备成功", res);
          uni.showToast({
            title: "连接成功",
            icon: "none",
          });
          uni.hideLoading();
          uni.setStorageSync("deviceData", e);
          this.deviceData = e;
          // 停止搜索
          uni.stopBluetoothDevicesDiscovery();
          // 获取设备的服务
          // tool.onBLEData(e.deviceId, (data) => {
          // 	console.log('拿到的数据', data)
          // })
        },
        fail: (err) => {
          console.error("连接蓝牙设备失败", err);
          uni.hideLoading();
          uni.showToast({
            title: "连接失败，请刷新后重试",
            icon: "none",
          });
        },
      });
    },
  },
  mounted() {},
  onUnload() {
    tool.closeOnBLE();
    // 停止搜索
    uni.stopBluetoothDevicesDiscovery();
  },
};
</script>
<style>
page {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  /* background-color: #f2f2f3; */
}

// 去掉页面滚动条
::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  -webkit-appearance: none;
  background: transparent;
}
</style>
<style lang="less" scoped>
.deviceConnectRow {
  font-family: "优设标题黑";
  // background-color: #f2f2f3;
  width: 100%;
  height: 100%;
  padding: 30px;

  .title {
    width: 100%;
    text-align: center;
    font-size: 24px;
  }

  .deviceSelect {
    .deviceItem {
      width: 304px;
      height: 63px;
      border-radius: 4px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 2px 4px 2px rgba(110, 88, 170, 0.2);
      padding: 14px 12px;
      display: flex;
      align-items: center;
      position: relative;
      margin: 0 auto;
      margin-top: 18px;

      .deviceLogo {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        background: rgba(110, 88, 170, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 7px;

        image {
          width: 25px;
          height: 25px;
          border-radius: 50%;
        }
      }

      .deviceInfo {
        .localName {
        }

        .introduce {
          font-size: 12px;
          color: rgba(124, 124, 126, 1);
        }
      }

      .selectIcon {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #6e58aa;
        position: absolute;
        right: 16px;
        top: 50%;
        transform: translate(0%, -50%);

        image {
          width: 12px;
          height: 12px;
          border-radius: 50%;
        }
      }
    }
  }

  .bluetoothRow {
    width: 100%;

    .tip {
      margin: 20px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .logo {
        display: flex;
        align-items: center;
        justify-content: center;

        image {
          width: 15px;
          height: 19px;
          margin-right: 6px;
        }

        .text {
        }
      }

      .switch {
        // width: 42px;
        // height: 19px;
        border-radius: 10px;
        background: rgba(110, 88, 170, 1);
        padding: 5px 10px;
        color: #fff;

        .cricle {
          width: 15px;
          height: 15px;
          border-radius: 50%;
          float: right;
          background: rgba(255, 255, 255, 1);
        }
      }
    }

    .bluetoothList {
      border-radius: 4px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 2px 4px 2px rgba(110, 88, 170, 0.2);
      width: 100%;
      padding: 8px 12px;

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 7px;

        .blueTitle {
        }

        .icon {
          image {
            width: 12px;
            height: 12px;
          }
        }
      }

      .bluetoothRow {
        height: 70vh;
        overflow-y: scroll;
      }

      .bluetoothItem {
        border-bottom: 1px solid rgba(124, 124, 126, 0.1);
        position: relative;
        margin-bottom: 7px;

        .bluetoothInfo {
          .name {
            color: rgba(124, 124, 126, 1);
          }

          .status {
            display: flex;
            align-items: center;

            text {
              font-size: 10px;
              color: rgba(124, 124, 126, 1);
              margin-right: 3px;
            }

            .statusEnegry {
              width: 2px;
              height: 7px;
              border-radius: 10px;
              background: rgba(110, 88, 170, 1);
              margin-right: 1px;
            }

            .statusEnegryNo {
              width: 2px;
              height: 7px;
              border-radius: 10px;
              background: rgba(191, 191, 191, 1);
              margin-right: 1px;
            }
          }

          .successSelect {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translate(0, -50%);

            image {
              width: 16px;
              height: 16px;
            }
          }
        }
      }
    }
  }

  .blueInfo {
    width: 100%;
    height: 111px;
    border-radius: 4px;
    background: rgba(110, 88, 170, 0.2);
    padding: 13px;
    margin-top: 20px;
    margin-bottom: 30px;

    .connectTitle {
      display: flex;
      align-items: center;

      image {
        width: 30px;
        height: 30px;
      }

      text {
        font-size: 16px;
        color: rgba(110, 88, 170, 1);
      }
    }

    .tipText {
      color: rgba(124, 124, 126, 1);
      margin-left: 25px;
    }
  }
}
</style>
